<?php


namespace app\models\user;


use think\Model;

use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;

class UserToken extends Model
{
    protected $name = 'user_token';

    protected $type = [
        'create_time' => 'datetime',
        'login_ip' => 'string'
    ];

    protected $autoWriteTimestamp = true;

    protected $updateTime = false;

    public static $leeway = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9';

    public static function onBeforeInsert(UserToken $token)
    {
        if (!isset($token['login_ip']))
            $token['login_ip'] = app()->request->ip();
    }

    /**
     * 创建token并且保存
     * @param $type 必要 用户ID
     * @return UserToken
     */
    public static function tokenCreate($type,$times)
    {
        $time = time(); //当前时间
//        $times = strtotime('+ 5000hour'); //
        $token  =[
                  "iss"=> "106.12.116.145",
                  "aud"=> "106.12.116.145",
                  "iat"=> $time,
                  "nbf"=> $time,
                  "exp"=> $times,
                  "data"=> [
                    "user_id"=> $type,
                  ]
              ];
        return JWT::encode($token,UserToken::$leeway);
    }

    /**
     * token解密
     * @param $type 必要 用户ID
     * @return UserToken
     */
    public static function tokenDecode($token)
    {
        $key = UserToken::$leeway;
        JWT::$leeway = 60;//当前时间减去60，把时间留点余地
        try {
            $decoded =JWT::decode($token, $key, ['HS256']); //HS256方式，这里要和签发的时候对应
            $decoded = json_decode(json_encode($decoded), true);
            if($decoded['exp']<time()) return 0;//失效token
            if(!is_numeric($decoded['data']['user_id']) || strpos($decoded['data']['user_id'],".")) return 0;//id有问题

            return $decoded['data']['user_id'];
        }catch(\Exception $e){
            return 0;//失败token
        }
    }
}